package main

import (
	"editor/constant"
	"editor/model"
	"editor/store"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http/httptest"
	"sort"
	"time"
)

func init() {
}
func main() {
	store.Init()
	ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
	ctx.Set(constant.RequestTime, time.Now().UnixMicro())

	list, err := GetMDFileInfoMapList()
	if err != nil {
		store.Panicf(ctx, err.Error(), "GetMDFileInfoMapListFailed")
	}

	for _, i := range list {
		if i.IsDir == 1 {
			err = syncDir(ctx, i)
			if err != nil {
				store.Panicf(ctx, err.Error(), "GetMDFileInfoMapListFailed")
			} else {
				store.Info(ctx, "insert success")
			}
			for _, m := range i.ChildList {
				err = syncFile(ctx, m, i)
				if err != nil {
					store.Panicf(ctx, err.Error(), "GetMDFileInfoMapListFailed")
				} else {
					store.Info(ctx, "insert success")
				}
			}
		} else {
			err = syncFile(ctx, i, nil)
			if err != nil {
				store.Panicf(ctx, err.Error(), "GetMDFileInfoMapListFailed")
			} else {
				store.Info(ctx, "insert success")
			}
		}
	}
}

func syncDir(c *gin.Context, i *constant.MDFile) (err error) {
	f := model.MdFile{
		//Id:           int64(i.Id),
		SortNum:      int64(i.Sort),
		CategoryName: i.Name,
		IsCategory:   1,
		IsShow:       1,
		IsDelete:     0,
		CreateTime:   time.Now().Unix(),
		UpdateTime:   time.Now().Unix(),
	}
	err = f.Add(c)

	return
}

func syncFile(c *gin.Context, i *constant.MDFile, parent *constant.MDFile) (err error) {
	filePath := constant.MDFileDir + "/" + i.FileName
	bt, _ := ioutil.ReadFile(filePath)
	f := model.MdFile{
		//Id:         int64(i.Id),
		MdTitle:    i.Name,
		MdContent:  string(bt),
		MdFilePath: constant.MDFileDir + "/" + i.FileName,
		MdFileSize: int64(len(string(bt))),
		SortNum:    int64(i.Sort),
		IsCategory: 0,
		IsShow:     1,
		IsDelete:   0,
		CreateTime: time.Now().Unix(),
		UpdateTime: time.Now().Unix(),
	}
	if parent != nil {
		f.CategoryID = int64(parent.Id)
		f.CategoryName = parent.Name
		f.Id = 0
		f.MdFilePath = constant.MDFileDir + "/" + parent.Name + "/" + i.FileName
	}
	err = f.Add(c)
	return
}

func GetMDFileInfoMapList() (files []*constant.MDFile, err error) {

	var arrTemp []constant.MDFile
	filesSortInfo, _ := ioutil.ReadFile(constant.DMInfosFile)
	if filesSortInfo != nil {
		_ = json.Unmarshal(filesSortInfo, &arrTemp)
	}

	mdFiles, err := ioutil.ReadDir(constant.MDFileDir)
	if err != nil {
		return nil, err
	}

	for _, mdFile := range mdFiles {
		fileName := mdFile.Name()
		if mdFile.IsDir() {
			cnf := GetMDFileInfoByConfig(arrTemp, fileName, "")
			dirItem := constant.MDFile{
				Id:       cnf.Id,
				Name:     fileName,
				FileName: fileName,
				FileSize: 0,
				Sort:     cnf.Sort,
				ModTime:  mdFile.ModTime().Unix(),
				Disable:  cnf.Disable,
				IsDir:    1,
			}

			mdChildFiles, _ := ioutil.ReadDir(constant.MDFileDir + "/" + fileName)
			for _, child := range mdChildFiles {
				if child.IsDir() {
					continue
				}
				if child.Name()[len(child.Name())-3:] != ".md" {
					continue
				}

				cnf := GetMDFileInfoByConfig(arrTemp, fileName, fileName)

				dirItem.ChildList = append(dirItem.ChildList, &constant.MDFile{
					Id:       0,
					Name:     child.Name()[:len(child.Name())-3],
					FileName: child.Name(),
					FileSize: child.Size(),
					Sort:     cnf.Sort,
					ModTime:  child.ModTime().Unix(),
					Disable:  cnf.Disable,
				})
			}

			files = append(files, &dirItem)
		} else {
			if fileName[len(fileName)-3:] != ".md" {
				continue
			}
			cnf := GetMDFileInfoByConfig(arrTemp, fileName, "")

			files = append(files, &constant.MDFile{
				Id:       cnf.Id,
				Name:     fileName[:len(fileName)-3],
				FileName: fileName,
				FileSize: mdFile.Size(),
				Sort:     cnf.Sort,
				ModTime:  mdFile.ModTime().Unix(),
				Disable:  cnf.Disable,
				IsDir:    0,
			})
		}
	}

	if len(files) == 0 {
		files = []*constant.MDFile{
			{
				Id:       1,
				Name:     "index",
				FileName: "index.md",
				FileSize: 0,
				Sort:     0,
				ModTime:  0,
			},
		}
	}

	sort.SliceStable(files, func(i, j int) bool {

		if len(files[i].ChildList) > 0 {
			sort.SliceStable(files[i].ChildList, func(m, n int) bool {
				return files[i].ChildList[m].Sort >= files[i].ChildList[n].Sort
			})
		}

		if len(files[j].ChildList) > 0 {
			sort.SliceStable(files[j].ChildList, func(m, n int) bool {
				return files[j].ChildList[m].Sort >= files[j].ChildList[n].Sort
			})
		}

		return files[i].Sort >= files[j].Sort
	})

	for i, j := range files {
		files[i].Id = i + 1
		for m, _ := range j.ChildList {
			files[i].ChildList[m].Id = m + 1
		}
	}

	return
}

func GetMDFileInfoByConfig(confArr []constant.MDFile, fileName, dirName string) (info *constant.MDFile) {
	if len(confArr) == 0 {
		return new(constant.MDFile)
	}

	for _, v := range confArr {
		if dirName == "" {
			if v.FileName == fileName {
				return &v
			}
		} else {
			if v.Name == dirName {
				for _, i := range v.ChildList {
					if i.FileName == fileName {
						return i
					}
				}
			}
		}
	}

	return new(constant.MDFile)
}
